package com.jushu.storbox.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.ExceptionConstant;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.service.ServiceFactory;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.util.image.ImageUtils;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.model.request.FolderCreateRequest;
import com.huawei.sharedrive.sdk.android.modelV2.request.LinkCreateRequestV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FileInfoResponseV2;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderResponse;
import com.huawei.sharedrive.sdk.android.modelV2.response.LinkInfoV2;
import com.huawei.sharedrive.sdk.android.service.handler.AsyncTaskHandler;

public class FileFolderAction extends Actions {

	private static final String TAG = FileFolderAction.class.getSimpleName();

    /** send from folder */
    private final static int sendFromCreateFolder = 1001;
    
    /** send from delete */
    private final static int sendFromDelete = 1002;
    
    /** send from Rename */
    private final static int sendFromRename = 1005;
    
    private Handler operationSuccessHandler = null;
	
	private Handler exceptionHandlers = null;
	
	public void setSuccessHandler(Handler handler) {
		operationSuccessHandler = handler;
	}
	
	public void setExceptionHandler(Handler handler) {
		exceptionHandlers = handler;
	}
	
    public interface OperationDispacher{

        public void onSuccess(int messageCode, Object obj);
        
        public void handleException(ClientException e, int messageCode, Object obj);
        
        public void onPrepare(int messageCode);
    
    }
    
	public FileFolderAction(Context context) {
		super(context);
	}

	public FileFolderInfo renameFile(
			ICloudDriveService service,
			String fileName, FileFolderInfo fileInformation, View item) {
		LogUtil.i(TAG, "renameFile[Actions]");
		FileFolderInfo info = null;
		if (ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					LogUtil.i(TAG , "start loginInV2[Actions]");
					loginInV2(service,
							PublicTools.getClientUserName(getContext()),
							PublicTools.getClientUserPassFail(getContext()), operationSuccessHandler);
					LogUtil.i(TAG, "loginIn_success[Actions]");
				} catch (ClientException e1) {
					e1.printStackTrace();
					handleException(e1, ClientConfig.SENDFROMLOGIN, null);// 1001
					return info;
				}
			}

			try {
				info = service.renameFile(getContext(), fileInformation, fileName);
				if(ImageUtils.isImageType(fileInformation.getName())){
					DirectoryUtil.deleteFileThumbnailPath(getContext(),fileInformation.getOwnerBy(), fileInformation.getId(), fileInformation.getName());
				}
				LogUtil.i(TAG, "renameFile_success[Actions]");
                Bundle fileBundle = new Bundle();
                fileBundle.putSerializable("entity", info);
                Message msg = operationSuccessHandler.obtainMessage(
                		UiConstant.SUCCESS_ON_FILE_FOLDER_INFO_CHANGED,sendFromRename,0,item);
                msg.setData(fileBundle);
                msg.sendToTarget();
			} catch (ClientException e) {
				LogUtil.e(TAG , e.getMessage());
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("FileFolderInfo", fileInformation);
				map.put("view", item);
				handleException(e, ClientConfig.SENDFROMRENAMEFILE, map);
			}
		}

		return info;
	}
	
	public FileFolderInfo renameFolder(
			ICloudDriveService service,
			String folderName, 
			FileFolderInfo fileInformation, View item) {
		LogUtil.i(TAG, "renameFolder[Actions]");
		FileFolderInfo info = null;
		if (ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					loginInV2(service,
							PublicTools.getClientUserName(getContext()),
							PublicTools.getClientUserPassFail(getContext()), operationSuccessHandler);
				} catch (ClientException e1) {
					e1.printStackTrace();
					handleException( e1, ClientConfig.SENDFROMLOGIN, null);// 1001
					return info;
				}
			}

			try {
				info = service.renameFolder(fileInformation, folderName);
				LogUtil.i(TAG, "renameFolder_success[Actions]");
                Bundle bundle = new Bundle();
                bundle.putSerializable("entity", info);
                bundle.putString("filePath", info.getLoctPath());
                Message msg = operationSuccessHandler.obtainMessage();
                msg.setData(bundle);
                msg.what = UiConstant.SUCCESS_ON_FILE_FOLDER_INFO_CHANGED;
                msg.arg1 = sendFromRename;
                msg.obj = item;
                msg.sendToTarget();
                
			} catch (ClientException e) {
				LogUtil.e(TAG , e.getMessage());
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("FileFolderInfo", fileInformation);
				map.put("view", item);
				handleException(e, ClientConfig.SENDFROMRENAMEFOLDER, map);
			}
		}
		return info;
	}

	public String deleteFile(ICloudDriveService service,
			FileFolderInfo fileInformation, View item) {
		LogUtil.i(TAG, "deleteAllFile[Actions]");
		String info = null;
		if (ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					loginInV2(service,
							PublicTools.getClientUserName(getContext()),
							PublicTools.getClientUserPassFail(getContext()), operationSuccessHandler);
				} catch (ClientException e1) {
					e1.printStackTrace();
					handleException(e1, ClientConfig.SENDFROMLOGIN, null);// 1001
					return info;
				}
			}
			
			try {
				info = service.deleteAllFile(fileInformation);
				LogUtil.i(TAG, "deleteAllFile_success[Actions]");
				Message msg = operationSuccessHandler.obtainMessage();
                msg.what = UiConstant.SUCCESS_ON_FILE_FOLDER_INFO_CHANGED;
                msg.arg1 = sendFromDelete;
                msg.obj = item;
                msg.sendToTarget();
			} catch (ClientException e) {
				e.printStackTrace();
				handleException(e, ClientConfig.SENDFROMDELETEFILE, item);
			}
		}
		return info;
	}
	
	public void deleteFileAsync(ICloudDriveService service,
			FileFolderInfo fileInformation, AsyncTaskHandler handler, View item) {
		LogUtil.i(TAG, "deleteAllFile[Actions]");
		if (ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
			try {
				service.deleteAllFileAsync(getContext(), fileInformation, handler);
			} catch (ClientException e) {
				handleException(e, ClientConfig.SENDFROMDELETEFILE, null);
			}
		}
	}
	
	public String deleteFolder(ICloudDriveService service,
			FileFolderInfo FileFolderInfomation, View item) {
		LogUtil.i(TAG, "deleteFolder[Actions]");
		String info = null;
		if (ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					loginInV2(service,
							PublicTools.getClientUserName(getContext()),
							PublicTools.getClientUserPassFail(getContext()), operationSuccessHandler);
				} catch (ClientException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					handleException(e1, ClientConfig.SENDFROMLOGIN, null);// 1001
					return info;
				}
			}
			
			try {
				
				info = service.deleteAllFolder(FileFolderInfomation);
				Message msg = operationSuccessHandler.obtainMessage();
				msg.what = UiConstant.SUCCESS_ON_FILE_FOLDER_INFO_CHANGED;
                msg.arg1 = sendFromDelete;
                msg.obj = item;
                msg.sendToTarget();
				LogUtil.i(TAG, "deleteFolder success[Actions]");
			} catch (ClientException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				LogUtil.e(TAG,
						"e_deleteAllFolder[Actions]:" + e.getStatusCode());
				handleException(e, ClientConfig.SENDFROMDELETEFOLDER, null);
			}
		}
		return info;
	}

	public void deleteFolderAsync(ICloudDriveService service,
			FileFolderInfo fileFolderInfomation, AsyncTaskHandler handler, View item) {
		LogUtil.i(TAG, "deleteFolder[Actions]");
		if (ShareDriveApplication.getInstance().
				getWifiController().networkIsAvailible()) {
			try {
				service.deleteAllFolderAync(fileFolderInfomation, handler);
				LogUtil.i(TAG, "deleteFolder success[Actions]");
			} catch (ClientException e) {
				LogUtil.e(TAG, "e_deleteAllFolder[Actions]:" + e.getStatusCode());
//				handleException(e, ClientConfig.SENDFROMDELETEFOLDER, null);
			}
		}
	}
	
	public String removeFile(ICloudDriveService service,
			FileFolderInfo file, FileFolderInfo targetFolder) {
		LogUtil.i(TAG, "removeFile[Actions]");
		String info = null;
		if (ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					loginInV2(service,
							PublicTools.getClientUserName(getContext()),
							PublicTools.getClientUserPassFail(getContext()), operationSuccessHandler);
				} catch (ClientException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
					return info;
				}
			}
			
			try {
				info = service.moveFile(file, targetFolder);
				operationSuccessHandler.sendEmptyMessage(UiConstant.SUCCESS_ON_FILE_FOLDER_REMOVE);
			} catch (ClientException e) {
				e.printStackTrace();
				handleException(e, ClientConfig.SENDFROMMOVEFILE, null);
				LogUtil.e(TAG, "removeFile statusCode:" + e.getStatusCode());
			}
		}
		return info;
	}

	public FolderResponse removeFolder(
			ICloudDriveService service,
			FileFolderInfo folder, FileFolderInfo targetFolder) {
		LogUtil.i(TAG, "removeFolder[Actions]");
		FolderResponse info = null;
		if (ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					loginInV2(service,
							PublicTools.getLoginUserName(getContext()),
							PublicTools.getLoginUserPassFail(getContext()), operationSuccessHandler);
				} catch (ClientException e1) {
					e1.printStackTrace();
					return info;
				}
			}
			
			try {
				info = service.moveFolder(folder, targetFolder);
				LogUtil.i(TAG, "removeFolder success[Actions]");
				operationSuccessHandler.sendEmptyMessage(UiConstant.SUCCESS_ON_FILE_FOLDER_REMOVE);
			} catch (ClientException e) {
				e.printStackTrace();
				LogUtil.e(TAG, "removeFoler fail:" + e.getStatusCode());
				handleException(e, ClientConfig.SENDFROMMOVEFOLDER, null);
			}
		}
		return info;
	}

	public LinkInfoV2 getLink(ICloudDriveService service,
			FileFolderInfo fileInformation, View item) {
		LogUtil.i(TAG, "setLink[Actions]");
		LinkInfoV2 info = null;
		if (ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					LogUtil.i(TAG, "start loginInV2[Actions]");
					loginInV2(service,
							PublicTools.getClientUserName(getContext()),
							PublicTools.getClientUserPassFail(getContext()), operationSuccessHandler);
					LogUtil.i(TAG, "loginIn_success[Actions]");
				} catch (ClientException e1) {
					e1.printStackTrace();
					handleException(e1, ClientConfig.SENDFROMLOGIN, null);// 1001
					return info;
				}
			}

			try {
//				info = service.getLink(fileInformation);
                Bundle fileInfoBundle = new Bundle();
                fileInfoBundle.putSerializable("FileFolderInfo", fileInformation);
                fileInfoBundle.putSerializable("LinkInfo", info);
                fileInfoBundle.putSerializable("LinkConfigInfo", Boolean.valueOf(service.isComplexLinkCode(ShareDriveApplication.getInstance()
			            .getAuthorization())));
                Message shareMsg = new Message();
                shareMsg.what = UiConstant.POPUP_SHARE_LINK_UI;
                shareMsg.setData(fileInfoBundle);
                shareMsg.obj = item;
                operationSuccessHandler.sendMessage(shareMsg);
                
			} catch (ClientException e) {
				if(e.getStatusCode() == ClientExceptionRelateHandler.ERROR_CODE_404_NO_RESOURCE && ClientExceptionRelateHandler.NoSuchLink.equals(e.getCode())){
					return createLink(service, fileInformation, item);
				}
				e.printStackTrace();
				handleException(e, ClientConfig.SENDFROMGETLINK, null);
			}
		}

		return info;
	}

	public LinkInfoV2 updateLink(ICloudDriveService service,
			FileFolderInfo fileInformation, LinkCreateRequestV2 linkRequest, View item) {
		LogUtil.i(TAG, "setLink[Actions]");
		LinkInfoV2 info = null;
		if (ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					LogUtil.i(TAG, "start loginInV2[Actions]");
					loginInV2(service,
							PublicTools.getClientUserName(getContext()),
							PublicTools.getClientUserPassFail(getContext()), operationSuccessHandler);
					LogUtil.i(TAG, "loginIn_success[Actions]");
				} catch (ClientException e1) {
					e1.printStackTrace();
					handleException(e1, ClientConfig.SENDFROMLOGIN, null);// 1001
					return info;
				}
			}

			try {
				info = service.updateLink(fileInformation, linkRequest);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("LinkInfo", info);
				map.put("view", item);
				LogUtil.i(TAG, "createLink_success[Actions]");
				Message msgObj1 = new Message();
            	msgObj1.obj = map;
            	msgObj1.what = ClientConfig.SENDFROMSHARELINK;
            	operationSuccessHandler.sendMessage(msgObj1);
			} catch (ClientException e) {
				e.printStackTrace();
				handleException(e, ClientConfig.SENDFROMSHARELINK, null);
			}
		}

		return info;
	}

	public LinkInfoV2 createLink(ICloudDriveService service,
			FileFolderInfo fileInformation, View item) {
		LogUtil.i(TAG, "setLink[Actions]");
		LinkInfoV2 info = null;
		if (ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					LogUtil.i(TAG, "start loginInV2[Actions]");
					loginInV2(service,
							PublicTools.getLoginUserName(getContext()),
							PublicTools.getLoginUserPassFail(getContext()), operationSuccessHandler);
					LogUtil.i(TAG, "loginIn_success[Actions]");
				} catch (ClientException e1) {
					e1.printStackTrace();
					handleException(e1, ClientConfig.SENDFROMLOGIN, null);// 1001
					return info;
				}
			}

			try {
				info = service.setLink(fileInformation);
				LogUtil.i(TAG, "createLink_success[Actions]");
				Bundle fileInfoBundle = new Bundle();
                fileInfoBundle.putSerializable("FileFolderInfo", fileInformation);
                fileInfoBundle.putSerializable("LinkInfo", info);
                fileInfoBundle.putSerializable("LinkConfigInfo", Boolean.valueOf(service.isComplexLinkCode(ShareDriveApplication.getInstance()
			            .getAuthorization())));
                Message shareMsg = new Message();
                shareMsg.what = UiConstant.POPUP_SHARE_LINK_UI;
                shareMsg.setData(fileInfoBundle);
                shareMsg.obj = item;
                operationSuccessHandler.sendMessage(shareMsg);
			} catch (ClientException e) {
				e.printStackTrace();
				handleException(e, ClientConfig.SENDFROMGETLINK, null);
			}
		}

		return info;
	}
	
	public int getNodeLinkedState(ICloudDriveService service,
	        FileFolderInfo fileInformation,View item)
    {
        LogUtil.i(TAG, "setLink[Actions]");
        int isSharelink = ClientConfig.NODE_SHARED_STATE_UNKNOWN;
        if (ShareDriveApplication.getInstance().getWifiController().getNetworkState())
        {
            if(PublicTools.isAuthiorzationGotoTimeout(getContext()))
            {
                try
                {
                    LogUtil.i(TAG, "start loginInV2[Actions]");
                    loginInV2(
                        service,
                        PublicTools.getClientUserName(getContext()),
                        PublicTools.getClientUserPassFail(getContext()),
                        operationSuccessHandler);
                    LogUtil.i(TAG, "loginIn_success[Actions]");
                }
                catch (ClientException e1)
                {
                    e1.printStackTrace();
                    handleException(e1, ClientConfig.SENDFROMLOGIN, null);// 1001
                    return isSharelink;
                }
            }

            try
            {
            	boolean isShared = false;
            	if (fileInformation.getIsFile() == 1)
                {
                    FileInfoResponseV2 fileNode = ServiceFactory.getRemoteFileService()
                    	.getFileResponse(fileInformation);
                    isShared = fileNode.isSharelink();
                }
                else
                {
                    FolderResponse folderNode = ServiceFactory.getRemoteFolderService().getFolderResponse(fileInformation.getOwnerId(), fileInformation.getId());
                    isShared = folderNode.getIsSharelink();
                }
            	
            	if(isShared){
            		isSharelink = ClientConfig.NODE_SHARED_STATE_TRUE;
            	} else {
            		isSharelink = ClientConfig.NODE_SHARED_STATE_FALSE;
            	}
            }
            catch (ClientException e)
            {
                e.printStackTrace();
                handleException( e, ClientConfig.SEND_FROM_GET_NODEINFOMATION, item);
            }
        }
        
        return isSharelink;
    }

	public FileFolderInfo createFolder(String ownerId,
			ICloudDriveService service, FolderCreateRequest request) {
		LogUtil.i(TAG, "createFolder[Actions]");
		FileFolderInfo info = null;

		if (ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
			if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
				try {
					loginInV2(service,
							PublicTools.getClientUserName(getContext()),
							PublicTools.getClientUserPassFail(getContext()), operationSuccessHandler);
				} catch (ClientException e1) {
					e1.printStackTrace();
					handleException(e1, ClientConfig.SENDFROMLOGIN, null);// 1001
					return info;
				}
			}

			try {
				info = service.createFolder(getContext(), ownerId, request);
				LogUtil.i(TAG, "createFolder_success[Actions]");
				 if (null != info)
                {
				 	Message msg = operationSuccessHandler.obtainMessage();
                    msg.obj = info;
                    msg.what = UiConstant.SUCCESS_ON_FILE_FOLDER_INFO_CHANGED;
                    msg.arg1 = sendFromCreateFolder;
                    operationSuccessHandler.sendMessage(msg);
                }
			} catch (ClientException e) {
				// TODO Auto-generated catch block
				LogUtil.e(TAG, "createFolder_e[Actions]:" + e.getStatusCode());
				e.printStackTrace();
				handleException( e, ClientConfig.SENDFROMCREATEFOLDER, null);
			}
		}

		return info;
	}

	/**
	 * @param service
	 * @param operationSuccessHandler
	 * @param obj
	 */
	public void uploadFileOrinitLogin(
			final ICloudDriveService service,
			final Object obj) {
		LogUtil.i(TAG, "uploadFileOrinitLogin[Actions]");
		if (ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
			new Thread(new Runnable() {
				public void run() {
					if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
						try {
							loginInV2(service,
									PublicTools.getClientUserName(getContext()),
									PublicTools.getClientUserPassFail(getContext()),
									operationSuccessHandler);
							Message msgObj = operationSuccessHandler.obtainMessage();
			            	msgObj.what = ClientConfig.SENDFROMUPLOADFILE;
			            	msgObj.obj = obj;
			            	msgObj.sendToTarget();
						} catch (ClientException e1) {
							e1.printStackTrace();
							handleException(e1, ClientConfig.SENDFROMLOGIN, null);// 1001
							return;
						}
					} else {
						Message msgObj = operationSuccessHandler.obtainMessage();
		            	msgObj.what = ClientConfig.SENDFROMUPLOADFILE;
		            	msgObj.obj = obj;
		            	msgObj.sendToTarget();
					}
				}

			}).start();

		} else {

		}
	}

	public void getAllFileListFromServer(final String ownerId, 
			final String folderId, final ICloudDriveService service,
			final int dir) {
		LogUtil.i(TAG, "getAllFileListFromServer[Actions]");
		new Thread(new Runnable() {
			public void run() {
				if (ShareDriveApplication.getInstance().getWifiController().getNetworkState()) {
					if (PublicTools.isAuthiorzationGotoTimeout(getContext())) {
						try {
							loginInV2(service,
									PublicTools.getClientUserName(getContext()),
									PublicTools.getClientUserPassFail(getContext()),
									operationSuccessHandler);
						} catch (ClientException e1) {
							e1.printStackTrace();
							handleException( e1, ClientConfig.SENDFROMGETRESOURCE, null);// 1001
							return;
						}
					}
					
					List<FileFolderInfo> resource = new ArrayList<FileFolderInfo>();
					try {
						if (null != service) {
							resource = service.getFileFolderListFromServer(
									getContext(), ownerId, folderId,
									PublicTools.getDes(getContext()),
									PublicTools.getOrderBy(getContext()), operationSuccessHandler);
							Message resourceMsg = new Message();
							resourceMsg.what = dir;
							resourceMsg.obj = resource;
		                    operationSuccessHandler.sendMessage(resourceMsg);
		                    
							LogUtil.i(TAG,
									"getAllFileListFromServer success[Actions]");
						}
					} catch (ClientException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						handleException( e, ClientConfig.SENDFROMGETRESOURCE, folderId);
						LogUtil.e(TAG, "getAllFileListFromServer[Action]_e:"
								+ e.getStatusCode());
					}
				} else {
					handleException( null, ClientConfig.SENDFROMGETRESOURCE, null);
				}
			}
		}).start();

	}
	
	private void handleException(ClientException e, int messageCode, Object obj)
    {
        Message msg = new Message();
        Bundle bundle = new Bundle();
        if (null != e)
        {
            LogUtil.e(TAG,
                "[Exception] webservice messageCode:" + messageCode + " | eStatusCode:"
                    + e.getStatusCode() + " | eCode:" + e.getCode() + " | eMsg:" + e.getMessage());
            msg.arg1 = messageCode;
            msg.what = e.getStatusCode();
            String code = "";
            if (null != e.getCode())
            {
                code = e.getCode();
                bundle.putString("code", code);
                msg.setData(bundle);
            }
            msg.obj = obj;
        }
        else
        {
            msg.arg1 = messageCode;
            msg.what = ExceptionConstant.access_internet_Failed;
        }
        exceptionHandlers.sendMessage(msg);
        
    }
}
